﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace SG.Sys.Console.CommandProcessing
{
    public class CommandHistory : ICommandHistory
    {
        private readonly IList<Entry> _entries;

        public CommandHistory(CommandParser parser)
        {
            _entries = new List<Entry>();
            Parser = parser;
        }

        public int Add(Entry entry)
        {
            var index = _entries.Count;
            _entries.Add(entry);
            SelectedIndex = null;

            return index;
        }

        public int? SelectedIndex { get; set; }

        public Entry SelectedOrLastEntry()
        {
            if (_entries.Count > 0)
            {
                if (!SelectedIndex.HasValue)
                    SelectedIndex = _entries.Count - 1;

                return _entries[SelectedIndex.Value];
            }
            return null;
        }

        public CommandParser Parser { get; private set; }

        public Entry this[int index]
        {
            get { return _entries[index]; }
        }

        private void IncDecOperator(Func<int, int, int> op)
        {
            var count = _entries.Count;
            if (count > 0 && SelectedIndex.HasValue)
            {
                var index = SelectedIndex.Value;
                SelectedIndex = op(index, count);
            }
            else
            {
                SelectedIndex = null;
            }
        }
        public void Up()
        {
            IncDecOperator((index, count) => (index + 1)%count);
        }
        public void Down()
        {
            IncDecOperator((index, count) => (count + index - 1)%count);
        }

        public IEnumerator<Entry> GetEnumerator()
        {
            return _entries.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

}
